import {XgPlayer} from "./index";

export class XgVideo {
  videoEl!: HTMLVideoElement;
  private canplay = false;

  constructor(private player: XgPlayer) {
    this.init();
  }
  private init() {
    const { src, controls, poster, preload, autoplay, resources } = this.player.config;
    this.videoEl = document.createElement('video');
    this.videoEl.src = src || resources[0]?.url || '';
    this.videoEl.controls = controls;
    this.videoEl.preload = preload;
    this.videoEl.poster = poster;
    if (autoplay) {
      this.videoEl.muted = true;
      this.videoEl.autoplay = autoplay;
    }
    this.player.container.appendChild(this.videoEl);
    this.initEvents();
  }
  private initEvents() {
    this.videoEl.addEventListener('canplay', () => {
      this.canplay = true;
      console.log('canplay');
      this.player.emitter.emit('canplay');
    });
    this.videoEl.addEventListener('playing', () => {
      this.player.emitter.emit('playing');
    });
    this.videoEl.addEventListener('pause', () => {
      this.player.emitter.emit('pause');
    });
    this.videoEl.addEventListener('timeupdate', () => {
      this.player.emitter.emit('timeupdate', this.videoEl.currentTime);
    });
    this.videoEl.addEventListener('ended', () => {
      this.player.emitter.emit('ended');
    });
    this.videoEl.addEventListener('error', () => {
      this.player.emitter.emit('error');
    });
  }
  play() {
    if (this.canplay) {
      this.videoEl.play();
    }
  }
  pause() {
    this.videoEl.pause();
  }
  seeking(time: number) {
    this.videoEl.currentTime = time;
  }
  changeResource(url: string) {
    const time = this.videoEl.currentTime;
    this.videoEl.src = url;
    this.seeking(time);
    this.play();
  }
}
